/*-----------------------------------------------------------------------------------
 *
 * 프로그램명	: CommonDAO.java
 * Version		: 1.0
 * 작성일 		: 2006-08-16
 * 작성자		:
 * 수정일 		:
 * 수정자		:
 * 설명		 	:
 * 기능		 	:
 *
 * Copyright (c) 2000 by H&H  All Rights Reserved.
 *
-------------------------------------------------------------------------------------*/
package com.qbooks.common;

import java.io.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.*;
import javax.servlet.http.*;

import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipInputStream;

import com.zll.framework.db.DBManager;
import com.zll.framework.model.HashList;
import com.zll.framework.util.StringUtil;



public class CommonUtil
{
	//싱글톤 구현
	private final static CommonUtil comm = new CommonUtil();
	private CommonUtil() {}
	public static CommonUtil getInstance() {
		return comm;
	}
	
	
	/**** 공통 코드 ****/
	private HashMap codeMap = new HashMap();

	/**** 리로드 공통코드 ****/
	public static void reloadCode() {
		comm.codeMap = new HashMap();
	}

	/**** 코드구분 조회 ****/
	public static HashList getCodeGubn(String code_gubn, String code_name) throws Exception
	{
		HashMap infos = new HashMap();
		infos.put("code_gubn", code_gubn);
		infos.put("code_name", code_name);
		return DBManager.executeQuery("/common.xml", "select_code_list", infos);
	}

	public static HashList getCodeList(String code_gubn) throws Exception
	{
		return getCodeList(code_gubn, null);
	}

	public static HashList getCodeList(String code_gubn, String allName) throws Exception
	{
		//System.out.println(code_gubn + ":" + comm.codeMap.toString());
		if (comm.codeMap.get(code_gubn) == null)
		{
			HashList list = null;

			if ("use_yn".equals(code_gubn))
			{
				list = new HashList();

				HashMap map = new HashMap();
				map.put("code", "Y");
				map.put("code_name", "사용");
				list.add(map);

				map = new HashMap();
				map.put("code", "N");
				map.put("code_name", "미사용");
				list.add(map);
			}
			else if ("category".equals(code_gubn)) {
				HashMap infos = new HashMap();
				infos.put("code_gubn", code_gubn);
				infos.put("use_yn", "Y");
				list = DBManager.executeQuery("/common.xml", "select_category_list", infos);
			}
			else if ("board_auth".equals(code_gubn)) {
				list = new HashList();

				HashMap map = new HashMap();
				map.put("code", "A");
				map.put("code_name", "관리자");
				list.add(map);

				map = new HashMap();
				map.put("code", "M");
				map.put("code_name", "회원");
				list.add(map);
			}
			else
			{
				HashMap infos = new HashMap();
				infos.put("code_gubn", code_gubn);
				infos.put("use_yn", "Y");
				list = DBManager.executeQuery("/common.xml", "select_code_list", infos);
			}

			//싱글톤 코드에 저장.
			comm.codeMap.put(code_gubn, list);

			//System.out.println("code map" + codeMap.toString());
		}


		HashList list = (HashList)comm.codeMap.get(code_gubn);


		if (allName == null) {
			return list;
		} else {
			HashList allList = new HashList();
			HashMap map = new HashMap();
			map.put("code", "");
			map.put("code_name", allName);
			allList.add(map);
			allList.add(list);

			return allList;
		}
	}

	public static HashList getCategoryList() throws Exception
	{
		HashMap infos = new HashMap();
		return DBManager.executeQuery("/common.xml", "select_category_list", infos);
	}

	public static HashMap getCode(String dept_gbn, String code_gubn, String code) throws Exception
	{
		HashMap infos = new HashMap();
		infos.put("dept_gbn", 	dept_gbn);
		infos.put("code_gubn", 	code_gubn);
		infos.put("code",		code);
		HashList HashList = DBManager.executeQuery("/common.xml", "select_code_list", infos);
		if (HashList.size() == 1) {
			return (HashMap)HashList.get(0);
		} else {
			return new HashMap();
		}
	}


	public static String nextDay(String from_date, int cnt) throws Exception
	{
		HashMap infos = new HashMap();
		infos.put("from_date", from_date);
		infos.put("cnt", 	String.valueOf(cnt));
		HashList cList = DBManager.executeQuery("/common.xml", "select_next_day", infos);
		return cList.get("to_date", 0);
	}







	/** 스토어 왼쪽 메뉴 */
	public static HashList getStoreMenuList() throws Exception
	{
		HashMap infos = new HashMap();
		return DBManager.executeQuery("/common.xml", "select_store_menu_list", infos);
	}

	public static String getReviewStar(int rate) {
		StringBuffer rateHtml = new StringBuffer();
		for (int i = 0; i < 5; i++) {
			if (i < rate) {
				rateHtml.append("★");
			} else {
				rateHtml.append("☆");
			}
		}
		return rateHtml.toString();
	}

	private static final byte[] buf = new byte[1024];
	
	/** 큐북.zip에서 index 파일 추출 */
	/**
    * Comment  : 
    */
    public static String getQBookHeader(String targetZip)throws Exception{
        ZipInputStream in = null;
        
        StringBuffer sb = new StringBuffer();
        
        try{
//            File fCompleteDir = null;
//            fCompleteDir = new File(completeDir);
//            if(isDirCre){
//                // 디렉토리가 없을경우 생성
//                fCompleteDir.mkdirs();
//            }
            
            // zip 파일의 input stream을 읽어들임
            in = new ZipInputStream(new FileInputStream(targetZip));
            ZipEntry entry = null;
            
           // FileOutputStream out = new FileOutputStream(completeDir + entry.getName());
            
            // input stream내의 압축된 파일들을 하나씩 읽어들임.
            while((entry = in.getNextEntry()) != null){
                //System.out.println("entry : " + entry);
                // zip 파일의 구조와 동일하게 가기위해 로컬의 디렉토리 구조를 만듬.
                String entryName = entry.getName();
                if (entryName.indexOf(".index") > -1) {
                	int bytes_read;
                    while((bytes_read = in.read(buf)) != -1){
                        System.out.println("bytes_read : " + bytes_read);
                    	//out.write(buf, 0, bytes_read);
                    	sb.append(new String(buf, "UTF-8"));
                    }
                    break;
                }
                
            }
            
            return sb.toString();
            
        }catch(Exception e){
            throw new Exception(e);
        }finally{
            // 모든 파일의 압축이 해제되면 input stream을 닫는다.
        	if (in != null) {
        		in.close();
        	}
        }
    }
    
    public static void updateDownloadCount(String appId) throws Exception {
    	HashMap infos = new HashMap();
		infos.put("app_id", appId);
		DBManager.executeUpdate("/admin.xml", "update_app_download_count", infos);
    }

    
    public static boolean isMobile(HttpServletRequest req) {
    	String agent = req.getHeader("USER-AGENT");

    	String[] mobileos = {"iPhone","iPod","Android","BlackBerry","Windows CE","Nokia","Webos","Opera Mini","SonyEricsson","Opera Mobi","IEMobile"};
    	
    	for(int i  =0; i < mobileos.length; i++) {
    		if (agent.indexOf(mobileos[i]) > -1) {
    			return true;
    		}
    	}
    	return false;
    }
    
    public static String getOrderNo() {
    	Calendar cal = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		return df.format(cal.getTime()) + StringUtil.lpad(String.valueOf((int)(Math.random()*1000000)),6,"0");
    }
    
    public static String getTimeStamp() {
    	Calendar cal = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		return df.format(cal.getTime());
    }
    
    public static String toCouponNo(String couponNo) {
    	return couponNo.substring(0,4) + "-" + couponNo.substring(4,8) + "-" + couponNo.substring(8,12) + "-" + couponNo.substring(12,16) ;
    }
    
    
    
//
//	public static String getCodeSelect(String code_gubn, String select_name, String select_value, int width) throws Exception
//	{
//		HashMap infos = new HashMap();
//		infos.put("code_gubn", code_gubn);
//		infos.put("use_yn", "Y");
//		HashList list = DBManager.executeQuery("/common.xml", "select_code_list", infos);
//
//		StringBuffer sb = new StringBuffer();
//		sb.append("<select name=\""+select_name+"\" style=\"width:"+width+"\">");
//		for (int i = 0; i < list.size(); i++) {
//			sb.append("<option value=\""+list.get("code",i)+"\" " + StringUtil.selected(list.get("code",i),select_value)+">"+list.get("code_name",i)+"</option>");
//		}
//		sb.append("</select>");
//
//		return sb.toString();
//	}


//	public static void insertLog(HttpServletRequest request) throws Exception
//	{
//		HashMap infos = new HashMap();
//		infos.put("main_path",		StringUtil.nvl(new String(request.getRequestURL())));
//		infos.put("user_name", 		StringUtil.nvl(request.getSession().getAttribute("session.user_name")));
//		infos.put("referer",		StringUtil.nvl(request.getHeader("referer")));
//		infos.put("ip_addr",		StringUtil.nvl(request.getRemoteAddr()));
//		infos.put("reg_user", 		StringUtil.nvl(request.getSession().getAttribute("session.user_id")));
//
//
//		DBManager.update("/common.xml", "insert_log", infos);
//	}

//	public static String toRegExp(String[] params) {
//		String infos = "";
//		if (params != null) {
//			for (int i = 0; i < params.length; i++) {
//				infos += params[i];
//				if (i < params.length-1)	infos += "|";
//			}
//		}
//		return infos;
//	}


//	public static String getCheckBox(String code_gubn, HashList list, String values) {
//
//		if (list == null) {
//			return "";
//		}
//		StringBuffer html = new StringBuffer();
//		String checked = "";
//		for (int i = 0; i < list.size(); i++) {
//			if (values.indexOf(list.get("code",i)) > -1) {
//				checked = " checked ";
//			} else {
//				checked = "";
//			}
//			html.append("<input type=\"checkbox\"")
//				.append(" name=\"s_").append(code_gubn).append("\"")
//				.append(checked)
//				.append(" value=\"").append(list.get("code",i)).append("\">")
//				.append(list.get("code_name",i)).append("\n");
//		}
//		return html.toString();
//	}
//
//	public static String getCheckBox(String code_gubn, HashMap map, String values) {
//		return getCheckBox(code_gubn, (HashList)map.get(code_gubn), values);
//	}
}
